<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2018/2/27
 * Time: 10:32
 */

namespace app\api\logic;

use think\Model;
use \think\Loader;
use app\common\utils\BuildStr as BuildStrUtil;

class UserBuy extends Model
{
    protected $userModel;
    protected $userCartModel;
    protected $userOrderModel;
    protected $userProfileLogic;

    protected function initialize()
    {
        parent::initialize();
        $this->userModel = Loader::model('User', 'model');
        $this->userCartModel = Loader::model('UserCart', 'model');
        $this->userOrderModel = Loader::model('UserOrder', 'model');
        $this->userProfileLogic = Loader::model('UserProfile', 'logic');
    }

    /**
     *  用户购物车列表
     * @param null
     * @return array
     */
    public function cart()
    {
        $list = $this->userModel->cart();
        $tree = array();
        foreach ($list as $k => $v) {
            if (!array_key_exists($v['shopId'], $tree)) {
                $tree[$v['shopId']] = array(
                    'shopId' => $v['shopId'],
                    'shopName' => $v['shopName'],
                    'products' => array()
                );
            }
            if (!array_key_exists($v['id'], $tree[$v['shopId']]['products'])) {
                $tree[$v['shopId']]['products'][$v['id']] = array(
                    'id' => $v['id'],
                    'productNum' => $v['productNum'],
                    'productId' => $v['productId'],
                    'productPrice' => $v['productPrice'],
                    'productAttr' => $v['productAttValue'],
                    'goodsId' => $v['goodsId'],
                    'goodsBrief' => $v['goodsBrief'],
                    'goodsImgUrl' => $v['goodsImgUrl'],
                    'shopId' => $v['shopId']
                );
            } else {
                $tree[$v['shopId']]['products'][$v['id']]['productAttr'] = $tree[$v['shopId']]['products'][$v['id']]['productAttr'] . $v['productAttValue'];
            }
        }
        $removedKeysTree = array_remove_keys($tree, 'products');
        return $removedKeysTree;
    }

    /**
     *  更新购物车产品数量
     * @param $num
     * @param $productId
     * @param $cartId
     * @return bool
     */
    public function updateCartProductNum($num, $productId, $cartId)
    {
        $result = $this->userCartModel->updateNum($num, $productId, $cartId);
        return $result;
    }

    /**
     *  获取确认订单页面信息
     * @param $ids
     * @return array
     */
    public function orderFirmInfo($ids)
    {
        $productList = $this->userCartModel->productList($ids);
        $defaultAddress = $this->userProfileLogic->defaultAddress();
        $data = [
            'product' => $productList,
            'address' => $defaultAddress
        ];
        return $data;
    }

    /**
     *  添加用户订单
     * @param $val
     * @return string
     */
    public function orderSubmit($val)
    {
        $order = $this->userOrderModel;
        $orderSn = BuildStrUtil::orderSn();
        $this->startTrans();
        try {
            $order->order_sn = $orderSn;
            $order->pay_type = $val['payId'];
            $order->express_id = $val['expressId'];
            $order->shipping_address_id = $val['shippingId'];
            if ($order->save()) {
                if ($order->orderBridgeProduct()->saveAll($val['product'])) {
                    $this->commit();
                    return $order->id;
                }
            }
        } catch (\Exception $e) {
            $this->rollback();
        }
    }

    /**
     *  订单支付信息
     * @param $
     * @return array
     */
    public function orderPayInfo($id)
    {
        $order = $this->userOrderModel;
        $data = $order->where(['id' => $id])
            ->field('id, order_sn as sn, create_time as createTime, expire_time as expireTime, actual_price as price, pay_type as payType')
            ->find();
        return $data;
    }
}